<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\util\wechat;

use app\common\model\MemberMiniapp;
use app\common\model\WechatOpenToken;
use EasyWeChat\Factory;

//微信公众号
use Exception;

class WechatMp
{

    /**
     * 微信开放平台配置 https://open.weixin.qq.com
     * @return
     */
    public function openConfig()
    {
        $info = bw_config('wechatopen');
        $config = [
            'app_id' => $info['app_id'],
            'secret' => $info['secret'],
            'token' => $info['token'],
            'aes_key' => $info['aes_key'],
            'log' => [
                'default' => 'dev', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => '/tmp/easywechat.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => '/tmp/easywechat.log',
                        'level' => 'info',
                    ],
                ],
            ],
        ];
        return Factory::openPlatform($config);
    }

    /**
     * #######################################
     * 编译生成JSSDK配置
     * @param array $jsApiList
     * @return json
     */
    public function jsApiList(int $app, $jsApiList = [])
    {
        if (empty($jsApiList)) {
            $jsApiList = ["checkJsApi", "invokeMiniProgramAPI", "launchMiniProgram", "hideMenuItems", 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'scanQRCode', "onMenuShareTimeline", "onMenuShareAppMessage", "closeWindow", "getNetworkType", "previewImage", "onVoiceRecordEnd", "onVoicePlayEnd", 'chooseWXPay', 'chooseCard', 'openCard', 'addCard', 'openAddress', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData'];
        }
        $url = request()->param('url');//如果前端传url值就重新设置加密参与参数url
        $jssdkObj = self::isTypes($app)->jssdk;
        if (isset($url)) $jssdkObj = self::isTypes($app)->jssdk->setUrl(urldecode($url));
        return $jssdkObj->buildConfig($jsApiList, false);
    }

    /**
     * #######################################
     * 判断程序是独立应用还是平台应用
     * @param integer $id程序服务ID
     * @return boolean
     */
    public function isTypes(int $id)
    {
        try {
            $app_info = MemberMiniapp::where(['id' => $id])->find();

            return empty($app_info->miniapp->is_openapp) ? self::official($id, $app_info) : self::openOfficial($id, $app_info);
        } catch (Exception $e) {
            return;
        }
    }

    /**
     * 微信基础配置
     * @param integer $id = 0 是读取后台系统的公众号配置
     */
    public function official(int $id = 0, $miniapp = [])
    {
        $config = [];
        if ($id) {
            if (empty($miniapp)) {
                $miniapp = MemberMiniapp::where(['id' => $id])->field('mp_appid,mp_secret')->find();
            }
            $config = ['app_id' => $miniapp['mp_appid'], 'secret' => $miniapp['mp_secret']];

        } else {
            //获取开放平台配置 TODO
            // $miniapp = bw_config('wechataccount');
            $miniapp = bw_config('scan');

            $config = ['app_id'  => $miniapp['mp_id'],'secret'  => $miniapp['mp_secret'],'token'   => $miniapp['mp_token'],'aes_key' => $miniapp['mp_aes_key']];
        }
        if (empty($config['app_id']) || empty($config['secret'])) {
            return false;
        }
        return Factory::officialAccount($config);//公众号操作实例
    }

    /**
     * 微信开放平台配置
     * @return void
     */
    public function openOfficial(int $id, $miniapp = [])
    {
        if (empty($miniapp)) {
            $miniapp = MemberMiniapp::where(['id' => $id])->field('mp_appid')->find();
        }
        if (empty($miniapp['mp_appid'])) {
            return false;
        }
        $refreshToken = WechatOpenToken::refreshToken($id, $miniapp['mp_appid']);
        if (empty($refreshToken)) {
            return false;
        }
        return self::openConfig()->officialAccount($miniapp['mp_appid'], $refreshToken['refreshToken']);
    }
}